package area

import (
	"context"
	"encoding/json"
	"git.mycaigou.com/gfyx/common/cache"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
)

const cacheTime = 7200
const cacheKey = "gfyx:all-area-list"

type areaConfigRepository struct {
	tenant_db.TenantDB
}

// NewAreaConfigRepository 构造函数
func NewAreaConfigRepository() AreaConfigRepositoryIface {
	return &areaConfigRepository{}
}

// AreaConfigList 获取Area列表数据
func (r *areaConfigRepository) AreaConfigList(ctx context.Context) ([]*GfyxAreaConfigPo, error) {
	//这个表的数据不会变，所以存一份到缓存中，提升查询效率
	cacheRedis, _ := cache.Redis()

	resp, err := cacheRedis.Get(ctx, cacheKey)
	if err != nil {
		return nil, err
	}
	var list []*GfyxAreaConfigPo
	if resp == "" {
		err := r.GetTenantDB(ctx).Where("is_deleted = ?", constants.IsDeletedFalse).Find(&list).Error
		if err != nil {
			return nil, err
		}
		bytes, _ := json.Marshal(list)
		_, _ = cacheRedis.Set(ctx, cacheKey, string(bytes), true, cacheTime)
	} else {
		_ = json.Unmarshal([]byte(resp), &list)
	}
	return list, nil
}

func (r *areaConfigRepository) GetAreaInfoByLikeName(ctx context.Context, areaName string, areaCodes []string) (*GfyxAreaConfigPo, error) {
	areaInfo := &GfyxAreaConfigPo{}
	areaName = areaName + "%"
	db := r.GetTenantDB(ctx).Where("is_deleted = ? and (item_name like ? or norm_name like ? )", constants.IsDeletedFalse, areaName, areaName)
	if len(areaCodes) > 0 {
		db.Where("parent_code in ? or item_code in ?", areaCodes, areaCodes)
	}

	err := db.First(areaInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	return areaInfo, nil
}

func (r *areaConfigRepository) GetAreaInfoByItemCode(ctx context.Context, itemCode []string) ([]*GfyxAreaConfigPo, error) {
	var areaList []*GfyxAreaConfigPo

	db := r.GetTenantDB(ctx).Where("is_deleted = ? and item_code in ?", constants.IsDeletedFalse, itemCode)

	err := db.Find(&areaList).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	return areaList, nil
}
